import React from 'react';
import { InputItem, Toast } from 'antd-mobile';
import CustomIcon from './Icon';

const wrapStyle = {
  marginTop: '5px',
  display: 'flex',
  justifyContent: 'flex-end',
  background: '#fff',
  padding: '0 10px',
};

export default class extends React.Component {
  constructor(props) {
    super(props);
    this.db = window.hornDB;
    this.state = {
      content: '',
      timeRange: {
        start: undefined,
        end: undefined,
      },
    }
  }

  componentDidMount() {
    this.input.focus();
  }

  /**
   * 添加条目，保存到数据库并更新视图
   */
  addItem = () => {
    const { timeRange, content } = this.state;
    if (!content) {
      Toast.info('请填写条目内容', 2, null, false);
      return;
    }
    timeRange.start = Date.now();
    this.db.insertRx({
      state: 1,
      timeRange,
      content,
    }).then(() => {
      this.setState({content: ''});
    });
  }

  /**
   * 修改输入框内容
   */
  changeContent = value => {
    this.setState({
      content: value,
    });
  }

  render() {
    const { content } = this.state;
    return <div style={wrapStyle}>
      <InputItem
        ref={r => {this.input = r}}
        value={content}
        onChange={this.changeContent}
        placeholder="添加一个条目" />
      <CustomIcon
        type="plus"
        onClick={this.addItem}
        style={{ flex: '0 0 22px', margin: '11px 5px', color: '#888' }} />
    </div>
  }
}